package com.demo.project_template.service.impl;

import com.demo.project_template.base.pay.alipay.model.Product;
import com.demo.project_template.base.pay.alipay.service.CpAliPayService;
import com.demo.project_template.base.pay.wxpay.common.WeChatPayConstants;
import com.demo.project_template.base.pay.wxpay.service.WechatPayService;
import com.demo.project_template.base.pay.wxpay.vo.WeChatCreateOrderVO;
import com.demo.project_template.base.pay.wxpay.vo.WeChatRefundVO;
import com.demo.project_template.constant.GoldEnum;
import com.demo.project_template.constant.OrderConstants;
import com.demo.project_template.entity.*;
import com.demo.project_template.exception.ErrorCodeException;
import com.demo.project_template.mapper.*;
import com.demo.project_template.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.demo.project_template.util.CommonUtil;
import com.demo.project_template.util.DateUtil;
import com.demo.project_template.vo.request.order.RechargeVO;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author 杨玉龙
 * @since 2023-06-19 15:56:43
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {
    @Resource
    private WechatPayService wechatPayService;
    @Resource
    private GoldRechargeMapper goldRechargeMapper;
    @Resource
    private VipRechargeMapper vipRechargeMapper;
    @Resource
    private CpAliPayService aliPayService;
    @Resource
    private UserGoldRecordService userGoldRecordService;
    @Resource
    private UserMapper userMapper;

    @Override
    public Map<String, String> rechargeGold(RechargeVO rechargeVO) {
        //构造出order对象
        Order order = getOrder(rechargeVO);

        if ("1".equals(rechargeVO.getPayType())) {
            return getWeChatPayMap(order);
        } else if ("2".equals(rechargeVO.getPayType())) {
            return getAliPayMap(order);
        } else {
            throw new ErrorCodeException("参数错误");
        }
    }

    private Map<String, String> getWeChatPayMap(Order order) {
        //构造微信支付VO
        WeChatCreateOrderVO weChatCreateOrderVO = new WeChatCreateOrderVO();
        weChatCreateOrderVO.setTotalPrice(order.getPrice().multiply(BigDecimal.valueOf(100)).intValue());
        weChatCreateOrderVO.setOutTradeNo(order.getOrderNo());
        weChatCreateOrderVO.setDescription(OrderConstants.PAY_NAME);
        weChatCreateOrderVO.setNotifyUrl(OrderConstants.RECHARGE_NOTIFY_URL);
        weChatCreateOrderVO.setPayType(WeChatPayConstants.WeChatPayAPP);
        return wechatPayService.createOrder(weChatCreateOrderVO);
    }


    private Map<String, String> getAliPayMap(Order order) {
        Product product = new Product();
        product.setSubject(OrderConstants.PAY_NAME);
        product.setOutTradeNo(order.getOrderNo());
        product.setTotalFee(String.valueOf(order.getPrice().multiply(BigDecimal.valueOf(100)).intValue()));
        aliPayService.appPay(product);
        return null;
    }

    @NotNull
    private Order getOrder(RechargeVO rechargeVO) {
        Order order = new Order();
        BeanUtils.copyProperties(rechargeVO, order);
        order.setOrderNo(CommonUtil.creatOrder());
        order.setState("0");
        if ("1".equals(rechargeVO.getType())) {
            GoldRecharge goldRecharge = goldRechargeMapper.selectById(rechargeVO.getTargetId());
            order.setCount(goldRecharge.getGlodCount());
            order.setPrice(goldRecharge.getPrice());
        } else if ("2".equals(rechargeVO.getType())) {
            VipRecharge vipRecharge = vipRechargeMapper.selectById(rechargeVO.getTargetId());
            order.setPrice(vipRecharge.getPrice());
            order.setCount(vipRecharge.getDaysCount());
        }
        save(order);
        return order;
    }

    @Override
    public void refundOrder(String orderNo) {
//        Order order = orderMapper.selectOne(new LambdaQueryWrapper<Order>().eq(Order::getOrderNo, orderNo));
//        if (CheckEmptyUtil.isEmpty(order) || Objects.equals("0",order.getState())){
//            throw new ErrorCodeException(ErrorCodeExceptionEnum.SYSTEM_ERROR);
//        }
//        //构造退款VO
//        WeChatRefundVO weChatRefundVO = getWeChatRefundVO(orderNo, refundPrice, order);
//        wechatPayService.refundOrder(weChatRefundVO);
//        orderMapper.updateById(order);
    }

    @NotNull
    private WeChatRefundVO getWeChatRefundVO(String orderNo, BigDecimal refundPrice, Order order) {
        WeChatRefundVO weChatRefundVO = new WeChatRefundVO();
        weChatRefundVO.setOut_trade_no(orderNo);
        weChatRefundVO.setOut_refund_no(CommonUtil.creatOrder());
        WeChatRefundVO.amount amount = new WeChatRefundVO.amount();
        amount.setRefund(refundPrice.multiply(BigDecimal.valueOf(100)).intValue());
        amount.setTotal(order.getPrice().multiply(BigDecimal.valueOf(100)).intValue());
        weChatRefundVO.setAmount(amount);
        return weChatRefundVO;
    }

    public void paySuccess(Order order) {
        if ("1".equals(order.getType())) {
            rechargeGold(order);
        } else {
            rechargeVIP(order);
        }
    }

    private void rechargeVIP(Order order) {
        //充值会员
        User user = userMapper.selectById(order.getUserId());
        VipRecharge vipRecharge = vipRechargeMapper.selectById(order.getTargetId());
        user.setIsMember("1");
        Date date;
        switch (vipRecharge.getType()) {
            case "0":
                date = DateUtil.changeDateByDay(new Date(), vipRecharge.getDaysCount());
                break;
            case "1":
                date = DateUtil.changeDateByMonth(new Date(), 1);
                break;
            case "2":
                date = DateUtil.changeDateByMonth(new Date(), 3);
                break;
            case "3":
                date = DateUtil.changeDateByYear(new Date(), 1);
                break;
            default:
                throw new ErrorCodeException("参数错误");
        }
        user.setMemberDeadline(date);
        userMapper.updateById(user);
    }

    private void rechargeGold(Order order) {
        //充值金币
        UserGoldRecord userGoldRecord = new UserGoldRecord();
        userGoldRecord.setUserId(order.getUserId());
        userGoldRecord.setAmount(order.getCount());
        userGoldRecord.setIsAdd("1");
        if (order.getPayType().equals("1")) {
            userGoldRecord.setType(GoldEnum.WECHAT_REGISTER_ADD.getCode());
            userGoldRecord.setReason(GoldEnum.WECHAT_REGISTER_ADD.getName());
        } else {
            userGoldRecord.setType(GoldEnum.ALIPAY_REGISTER_ADD.getCode());
            userGoldRecord.setReason(GoldEnum.ALIPAY_REGISTER_ADD.getName());
        }
        userGoldRecordService.add(userGoldRecord);
    }
}
